package com.mongo.demo;

import com.mongo.demo.mapper.EntInfoMapper;
import com.mongo.demo.model.InvoiceRiskDocument;
import com.mongo.demo.service.InvoiceRiskDocumentGenerationService;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;


@Component
@Order(1)
public class StartService implements ApplicationRunner {

    @Autowired
    private InvoiceRiskDocumentGenerationService invoiceRiskDocumentGenerationService;

    @Autowired
    private EntInfoMapper entInfoMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void run(ApplicationArguments args) {

//        InvoiceRiskDocument invoiceRiskDocument = invoiceRiskDocumentGenerationService.generationDocument("杭州博联智能科技股份有限公司","123");
//        mongoTemplate.save(invoiceRiskDocument);

//        List<InvoiceRiskDocument> invoiceRiskDocuments = invoiceRiskDocumentGenerationService.generationDocuments();
//        mongoTemplate.insert(invoiceRiskDocuments,InvoiceRiskDocument.class);

//        List<EnterpriseInfo> enterpriseInfos = entInfoMapper.getEntInfos();
//        mongoTemplate.insert(enterpriseInfos,EnterpriseInfo.class);

        Query query = Query.query(Criteria.where("entName").is("广州市军恩化工科技有限公司"));

        InvoiceRiskDocument queryEntity = mongoTemplate.findOne(query,InvoiceRiskDocument.class);

        //Update的方法一，可支持局部key修改，用map作为数据结构操作比较方便
        Update update = new Update();
        update.set("invoiceIndicators.近12个月超过去年收入均值的90%的次数", "1111111111");
        mongoTemplate.updateFirst(query,update, InvoiceRiskDocument.class);

        //Update的方法二，可支持局部key修改，用Bean作为数据结构操作比较方便
        InvoiceRiskDocument invoiceRiskDocument = InvoiceRiskDocument.builder().entName("广州市军恩化工科技有限公司1").build();
        Document document = new Document();
        mongoTemplate.getConverter().write(invoiceRiskDocument,document);
        //加上"$set"作为参数可以实现局部更新
        Update update1 = Update.fromDocument(new Document("$set",document));
        mongoTemplate.updateFirst(query,update1,InvoiceRiskDocument.class);
        //不加"$set"全局更新
        Update update2 = Update.fromDocument(document);
        mongoTemplate.updateFirst(query,update1,InvoiceRiskDocument.class);

        
    }
} 
